package com.example.mindadinner.net;

import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class RequestManager {
	private Map<Long, OnRequestResponseListener> listeners = new HashMap<Long, OnRequestResponseListener>();
	private Map<Long, Request> requests = new HashMap<Long, Request>();

	static class RequestManagerHolder {
		static RequestManager instance = new RequestManager();
	}

	public static RequestManager getInstance() {
		return RequestManagerHolder.instance;
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.obj == null) {
				return;
			}
			final Bundle bundle = (Bundle) msg.obj;
			final long requestId = bundle
					.getLong(RequestThread.BUNDLE_NAME_REQUEST_ID);
			final RequestResult result = (RequestResult) bundle
					.get(RequestThread.BUNDLE_NAME_RESULT);
			/*
			 * 除去监听者和需求
			 */
			final OnRequestResponseListener listener = listeners.remove(requestId);
			final Request request =requests.remove(requestId);
			
			
			if (listener != null && result instanceof NetErrRequestResult) {
				listener.onRequestNetError(requestId, request, (NetErrRequestResult) result);
			}else if(listener != null && result instanceof SuccessRequestResult){
				listener.OnRequestSucess(requestId, request, (SuccessRequestResult) result);
			}else if(listener != null && result instanceof ApiErrResult){
				listener.onRequestApiError(requestId, request, (ApiErrResult) result);
			}
		}

	};

	public synchronized long startRequest(OnRequestResponseListener listener,
			Request request) {
		/*
		 * 检查需求是否重复
		 */
		final long existRequest=getDuplicateRequest(request);
		if(existRequest>-1){
			return existRequest;
		}
		/*
		 * 利用反射建立相应的线程并执行 将返回的信息封装RequestReasult的子类返回 并根据返回类型回调监听者的不同方法
		 */
		final RequestThread thread = RquestFactory.createRequestThread(request,
				handler);
		
		if (thread != null) {
			long requestId = thread.getRequestId();
			RequestPool.execute(thread);
			/*
			 * 将不重复的监听者 和需求放入列表
			 */
			listeners.put(requestId, listener);
			requests.put(requestId, request);
			return requestId;
		}
		return -1;
	}
	public long getDuplicateRequest(Request request){
		
		for(final Map.Entry<Long, Request> entry:requests.entrySet()){
			if(entry.getValue().isDuplicated(request)){
				return entry.getKey();
			}
		}
		return -1;
	}

}